package com.hanhai.material.config.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultCode;
import com.hanhai.material.common.result.ResultTool;

import com.hanhai.material.utils.jwt.JWTUtil;
import com.hanhai.material.utils.redis.RedisUtil;
import com.hanhai.material.wages.entity.SysUser;
import com.hanhai.material.wages.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author youchuang
 * @description:权限过滤
 **/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JWTUtil jwtUtil;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    SysUserService sysUserService;


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String token = request.getHeader(jwtUtil.getHeader());
        logger.warn("JWT:" + token);
        if (StrUtil.isBlankOrUndefined(token)) {
            chain.doFilter(request, response);
            return;
        }
        String username = JWTUtil.getUsername(token);
        if (this.redisUtil.hget(username, "token") == null) {
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            Result<?> result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
            outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();
            chain.doFilter(request, response);
            return;
        }
        // 获取用户的权限等信息
        SysUser sysUser = sysUserService.getByUsername(username);

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        chain.doFilter(request, response);
    }
}
